const Koa = require('koa');
const KoaRouter = require('koa-router');
const KoaCors = require('koa2-cors');
const KoaBodyparser = require('koa-bodyparser');


const app = new Koa();
const router = new KoaRouter();
const subRouter = new KoaRouter();


subRouter.get('/', ctx => {
  ctx.body = ctx.url;
})
subRouter.get('/:id', ctx => {
  ctx.body = ctx.params;
})

router.prefix('/api');
router.get('/user/:id', ctx => {
  console.log('in get');
  // ctx.status = 200;
  ctx.body = `<h1> USERNAME: ${ctx.query.name} USERID: ${ctx.params.id}</h1>`
})

router.post('/user', ctx => {
  console.log('in post:', ctx.request.body);

  ctx.status = 200;
  ctx.body = 'response for post';
})
router.use('/admin/:id/man', subRouter.routes(), subRouter.allowedMethods());


// 挂载跨域中间件
app.use(KoaCors({
  origin: function(ctx) {
    return 'http://localhost:3000';
  },
  maxAge: 5,
  credentials: true,
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept']

}))

// 挂载 bodyparser 中间件
app.use(KoaBodyparser());

 
// 挂载路由中间件
app
  .use(router.routes())
  .use(router.allowedMethods());



app.listen(1314, () => {
  console.log(`服务在 http://localhost:1314 上启动起来了`);
})